package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("FoodbatchmaterialRestController")
public class FoodbatchmaterialRestController extends CmiEmaController {

	/**
	 * Create a new Foodbatchmaterial entity
	 * 
	 */
	@RequestMapping(value = "/newFoodbatchmaterial", method = RequestMethod.POST)
	@ResponseBody
	public Object newFoodbatchmaterial(@RequestBody Foodbatchmaterial foodbatchmaterial) {
		foodbatchmaterialService.saveFoodbatchmaterial(foodbatchmaterial);
		return JSONObject.parse(cmiPsonService
				.toJsonString(foodbatchmaterialDAO.findFoodbatchmaterialByPrimaryKey(foodbatchmaterial.getId()), 2));
	}

	@RequestMapping(value = "/restNewFoodbatchmaterial", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewFoodbatchmaterial(@RequestBody String foodbatchmaterialJson) {
		Foodbatchmaterial foodbatchmaterial = new Gson().fromJson(foodbatchmaterialJson, Foodbatchmaterial.class);
		appendReferences(foodbatchmaterial);
		foodbatchmaterialService.saveFoodbatchmaterial(foodbatchmaterial);
		return JSONObject.parse(cmiPsonService
				.toJsonString(foodbatchmaterialDAO.findFoodbatchmaterialByPrimaryKey(foodbatchmaterial.getId()), 2));
	}

	@RequestMapping(value = "/saveFoodbatchmaterial", method = RequestMethod.PUT)
	@ResponseBody
	public Foodbatchmaterial saveFoodbatchmaterial(@RequestBody Foodbatchmaterial foodbatchmaterial) {
		foodbatchmaterialService.saveFoodbatchmaterial(foodbatchmaterial);
		return foodbatchmaterialDAO.findFoodbatchmaterialByPrimaryKey(foodbatchmaterial.getId());
	}

	@RequestMapping(value = "/restSaveFoodbatchmaterial", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveFoodbatchmaterial(@RequestBody String foodbatchmaterialJson) {
		Foodbatchmaterial foodbatchmaterial = new Gson().fromJson(foodbatchmaterialJson, Foodbatchmaterial.class);
		appendReferences(foodbatchmaterial);
		CmiPsonService cmiPsonService = new CmiPsonService();
		foodbatchmaterialService.saveFoodbatchmaterial(foodbatchmaterial);
		return JSONObject.parse(cmiPsonService
				.toJsonString(foodbatchmaterialDAO.findFoodbatchmaterialByPrimaryKey(foodbatchmaterial.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteFoodbatchmaterial/{foodbatchmaterialId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteFoodbatchmaterial(@PathVariable Integer foodbatchmaterialId) {
		Foodbatchmaterial foodbatchmaterial = foodbatchmaterialDAO
				.findFoodbatchmaterialByPrimaryKey(foodbatchmaterialId);
		foodbatchmaterialService.deleteFoodbatchmaterial(foodbatchmaterial);
	}

	@RequestMapping(value = "/restConfirmDeleteFoodbatchmaterials")
	@ResponseBody
	public Object restConfirmDeleteFoodbatchmaterials(@RequestBody Set<Integer> deleteFoodbatchmaterialsIds) {
		Set<Foodbatchmaterial> deleteFoodbatchmaterials = foodbatchmaterialDAO
				.findFoodbatchmaterialsByIds(deleteFoodbatchmaterialsIds);
		Set<Foodbatchmaterial> referencedFoodbatchmaterials = foodbatchmaterialService
				.loadReferenceFoodbatchmaterials(deleteFoodbatchmaterials);
		deleteFoodbatchmaterials.removeAll(referencedFoodbatchmaterials);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedFoodbatchmaterials);
		jsonObject.put("deleteEntitys", deleteFoodbatchmaterials);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteFoodbatchmaterials")
	@ResponseBody
	public Object restDeleteFoodbatchmaterials(@RequestBody Set<Foodbatchmaterial> deleteFoodbatchmaterials) {
		Iterator<Foodbatchmaterial> iterator = deleteFoodbatchmaterials.iterator();
		while (iterator.hasNext()) {
			Foodbatchmaterial currentFoodbatchmaterial = iterator.next();
			foodbatchmaterialService.deleteFoodbatchmaterial(currentFoodbatchmaterial);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listFoodbatchmaterials");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadFoodbatchmaterial/{foodbatchmaterialId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodbatchmaterial(@PathVariable Integer foodbatchmaterialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(foodbatchmaterialDAO.findFoodbatchmaterialByPrimaryKey(foodbatchmaterialId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodbatchmaterialFoodbatch/{foodbatchmaterialId}/foodbatch", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodbatchmaterialFoodbatch(@PathVariable Integer foodbatchmaterialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				foodbatchmaterialDAO.findFoodbatchmaterialByPrimaryKey(foodbatchmaterialId).getFoodbatch(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodbatchmaterialMaterial/{foodbatchmaterialId}/material", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodbatchmaterialMaterial(@PathVariable Integer foodbatchmaterialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				foodbatchmaterialDAO.findFoodbatchmaterialByPrimaryKey(foodbatchmaterialId).getMaterial(), 2,
				cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	public void appendReferences(Foodbatchmaterial foodbatchmaterial) {

		Foodbatch foodbatch = foodbatchmaterial.getFoodbatch();
		if (foodbatch != null)
			foodbatchmaterial.setFoodbatch(foodbatchService.findFoodbatchByPrimaryKey(foodbatch.getId()));

		Material material = foodbatchmaterial.getMaterial();
		if (material != null)
			foodbatchmaterial.setMaterial(materialService.findMaterialByPrimaryKey(material.getId()));

	}

	@RequestMapping(value = "/restGetFoodbatchmaterialFoodbatch/{foodbatchmaterialId}/foodbatch", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodbatchmaterialFoodbatch(@PathVariable Integer foodbatchmaterialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				foodbatchmaterialDAO.findFoodbatchmaterialByPrimaryKey(foodbatchmaterialId).getFoodbatch(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodbatchmaterialMaterial/{foodbatchmaterialId}/material", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodbatchmaterialMaterial(@PathVariable Integer foodbatchmaterialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				foodbatchmaterialDAO.findFoodbatchmaterialByPrimaryKey(foodbatchmaterialId).getMaterial(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restListFoodbatchmaterials", method = RequestMethod.GET)
	@ResponseBody
	public Object restListFoodbatchmaterials() {
		return JSONObject.parse(cmiPsonService.toJsonString(foodbatchmaterialService.loadFoodbatchmaterials(), 2));
	}

	@RequestMapping(value = "/restListFoodbatchmaterialsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListFoodbatchmaterialsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = foodbatchmaterialPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Foodbatchmaterial> foodbatchmaterials = foodbatchmaterialDAO.findAllFoodbatchmaterials(startResult,
				cmiPagination.getPaginationSize());
		String foodbatchmaterialString = cmiPsonService.toPsonString(foodbatchmaterials, 2, cmiPagination);

		return JSONObject.parse(foodbatchmaterialString);
	}

	@RequestMapping("/foodbatchmaterialSelectBox")
	@ResponseBody
	public JSONObject foodbatchmaterialSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Foodbatch":
				entitySet = foodbatchService.loadFoodbatchsByIdSet(searchValue);
				break;
			case "Material":
				entitySet = materialService.loadMaterialsByIdSet(searchValue);
				break;

			// 被引用键
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Foodbatch":
				entitySet = foodbatchDAO.findAllFoodbatchs((pageNumber - 1) * paginationSize, paginationSize);
				count = foodbatchService.countFoodbatchs();
				break;
			case "Material":
				entitySet = materialDAO.findAllMaterials((pageNumber - 1) * paginationSize, paginationSize);
				count = materialService.countMaterials();
				break;

			// 被引用键
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Foodbatch":
				entitySet = foodbatchDAO.findFoodbatchByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodbatchService.countFoodbatchsByName(queryword);
				break;
			case "Material":
				entitySet = materialDAO.findMaterialByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = materialService.countMaterialsByName(queryword);
				break;

			// 被引用键
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
